/**
 * @description  资金明细
 * @author shenhong
 */
import accounting from 'accounting';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';

import bugImg from '../../../assets/commom/buy.png';
import sellImg from '../../../assets/commom/sell.png';
import myStyle from './index.less';

import { ContentPackage, DATA_ENTRY, TableC, AdvancedSearch } from '../../../comps';
import colorArr from '../../../css/colors.js';

@Form.create()
class CapitalDetails extends PureComponent {
  constructor() {
    super();
    this.state = {
      dataRange: [moment(), moment()],
      formData: { startDate: moment(), endDate: moment() },
      current: 1,
      pageSize: 20,
      sortedInfo: {},
      isReset: false,
      // 带md是判断买断式
      operateType: [
        '48',
        '44_45',
        '47_48',
        '49_50',
        '52_53',
        '67',
        '69',
        '1006',
        '1007',
        '66_67',
        '68_69',
        '48_md',
        '44_45_md',
        '47_48_md',
        '49_50_md',
        '52_53_md',
        '67_md',
        '69_md',
        '1006_md',
        '1007_md',
        '66_67_md',
        '68_69_md',
      ],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    // 资产类型字典
    const {
      globalM: {
        dataDictionary: { OPERATE_TYPE_DICT = [] },
      },
    } = this.props;
    dispatch({
      type: 'capitalDetailsM/save',
      payload: {
        typeData: OPERATE_TYPE_DICT,
      },
    });
    this.searchData();
  }
  // 离开时重新设置是否重置判断
  componentWillUnmount() {
    this.setState({
      isReset: false,
    });
  }

  // 改变数据格式
  changeData = (e) => {
    const data = [];
    if (e && e.length) {
      e.map((item) => {
        data.push({
          title: item.value,
          value: item.code,
        });
      });
    }
    return data;
  };

  // 查询数据
  searchData = () => {
    const { formData } = this.state;
    const { dispatch } = this.props;
    const data = {
      search_GTE_dataDt: formData?.startDate.format('YYYYMMDD'),
      search_LTE_dataDt: formData?.endDate.format('YYYYMMDD'),
    };
    formData.combCodes ? (data.combCodes = formData.combCodes) : null;
    formData.search_EQ_operateType ? (data.search_EQ_operateType = formData.search_EQ_operateType) : null;

    data.page = {
      current: 1,
      pageSize: 20,
    };
    dispatch({
      type: 'capitalDetailsM/getSearch',
      payload: data,
    });
  };

  // 表格排序
  tableChange = (pagination, filt, sorter) => {
    const { formData, isReset } = this.state;
    const { dispatch } = this.props;
    this.setState({
      sortedInfo: sorter,
    });
    const data = {
      search_GTE_dataDt: formData?.startDate.format('YYYYMMDD'),
      search_LTE_dataDt: formData?.endDate.format('YYYYMMDD'),
    };
    data.page = {
      current: pagination.current,
      pageSize: pagination.pageSize,
    };
    formData.combCodes ? (data.combCodes = formData.combCodes) : null;
    formData.search_EQ_operateType ? (data.search_EQ_operateType = formData.search_EQ_operateType) : null;
    if (sorter.order !== undefined) {
      data.columnKey = sorter.columnKey;
      if (sorter.order == 'descend') {
        data.order = 'desc';
      } else if (sorter.order == 'ascend') {
        data.order = 'asc';
      } else {
        data.order = '';
      }
    }
    if (isReset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    dispatch({
      type: 'capitalDetailsM/getSearch',
      payload: data,
    });
  };

  // 业务类型前加图标
  chengeStyle = (text) => {
    const {
      capitalDetailsM: { typeData },
    } = this.props;
    let code = '';
    let test = '';
    if (typeData && typeData.length) {
      typeData.map((item) => {
        if (text == item.code) {
          code = item.pid;
          test = item.value;
        }
      });
    }
    return (
      <div>
        {/* eslint-disable-next-line jsx-a11y/alt-text */}
        <img src={code == '0' ? bugImg : sellImg} />
        <span style={{ marginLeft: '10px' }}>{test}</span>
      </div>
    );
  };

  // 改变发生金额的颜色
  redAndGreen = (text, record, num) => {
    const {
      capitalDetailsM: { typeData },
    } = this.props;
    const textColor = colorArr.debtAndProfit.text;
    let code = '';
    if (typeData && typeData.length) {
      typeData.map((item) => {
        if (record.operateType == item.code) {
          code = item.pid;
        }
      });
    }
    const tet = Number(text)
      .toFixed(num)
      .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    const colors = code == '1' ? textColor[0] : textColor[1];
    return <span style={{ color: `${colors}` }}>{tet}</span>;
  };

  // 处理千分位
  changeRender = (text, num) => {
    const test = Number(text)
      .toFixed(num)
      .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

    return test;
  };

  // 处理表格样式展示
  changeColumns = (columns) => {
    const data = columns;
    const { sortedInfo } = this.state;
    if (data && data.length) {
      data.map((item) => {
        if (item.key == 'handleDate') {
          // 交易时间排序
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'handleDate' && sortedInfo.order;
          item.width = 120;
          item.render = (text, record) => (text !== null ? text : record.dataDt);
        }
        if (item.key == 'combName') {
          // 产品名称转为代码-简称
          item.width = 180;
          item.render = (text, record) => `${record.rootId}-${record.rootName}`;
        }
        if (item.key == 'weight') {
          // 组合名称转为代码-简称
          item.width = 180;
          item.render = (text, record) => `${record.combCode}-${record.combName}`;
        }
        if (item.key == 'tradingCode') {
          // 证券代码转为代码-简称
          item.width = 180;
          item.render = (text, record) => (record.tradingName ? `${record.tradingCode}-${record.tradingName}` : record.tradingCode || '--');
        }
        if (item.key == 'operateType') {
          item.width = 160;
          item.render = (text) => this.chengeStyle(text);
        }
        if (item.key == 'balance') {
          item.align = 'right';
          item.width = 100;

          item.render = (text, record) => {
            if (this.state.operateType.some((i) => i == record.operateType)) {
              return text !== null ? this.redAndGreen(text, record, 2) : '--';
            }
            return text !== null ? this.redAndGreen(text, record, 4) : '--';
          };
        }
        if (item.key == 'balancepre' || item.key == 'balanceafter') {
          item.align = 'right';
          item.width = 100;
          item.render = (text, record) => {
            if (this.state.operateType.some((i) => i == record.operateType)) {
              return text !== null ? this.changeRender(text, 2) : '--';
            }
            return text !== null ? this.changeRender(text, 4) : '--';
          };
        }
        if (item.key == 'currency') {
          item.width = 60;
        }
        if (item.key == 'amount') {
          item.type = 'number';
          item.align = 'right';
          item.width = 100;
          item.render = (text, record) => {
            if (this.state.operateType.some((i) => i == record.operateType)) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), 2);
          };
        }
      });
    }
    return data;
  };

  // 渲染表格
  tableRender = () => {
    const {
      capitalDetailsM: { tableData },
      loading,
    } = this.props;
    const { dataSource } = tableData.data;
    const columns = this.changeColumns(tableData.data.columns);
    const { pageInfo } = tableData.data;
    return (
      <div>
        <TableC
          columns={columns}
          dataSource={dataSource}
          loading={loading}
          onChange={this.tableChange}
          current={pageInfo.currentPage}
          total={pageInfo.total}
          pageSize={pageInfo.numInPage}
          rowKey='key'
          scroll={{ x: 'max-content' }}
          selfScrollY
        />
      </div>
    );
  };

  render() {
    const {
      capitalDetailsM: { typeData },
    } = this.props;
    const selectData = this.changeData(typeData); // 将接口返回数据改成组件需要的格式
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: this.state.dataRange,
          hasDataED: moment(),
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
        },
        {
          dataIndex: 'combCodes',
          title: '组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'], // 不支持选估值解析模式的产品
        },
        {
          dataIndex: 'search_EQ_operateType',
          title: '资产类型',
          type: DATA_ENTRY.SELECT,
          dataSource: selectData,
          allowClear: true,
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            formData: e,
            isReset: false,
          },
          () => {
            this.searchData();
          },
        );
      },
      onClear: () => {
        const { form } = this.props;
        form.resetFields();
        const { formData } = this.state;
        if (moment().format('YYYYMMDD') == formData?.startDate.format('YYYYMMDD') && moment().format('YYYYMMDD') == formData.endDate.format('YYYYMMDD')) {
          if (formData.combCodes || formData.search_EQ_operateType) {
            this.setState({
              isReset: true,
            });
          }
        } else {
          this.setState({
            isReset: true,
          });
        }
      },
    };

    return (
      <ContentPackage
        title='资金明细'
        contentHtml={
          <div className={myStyle.bodyArea}>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            <div style={{ marginTop: '10px', overflow: 'auto' }}>{this.tableRender()}</div>
          </div>
        }
      />
    );
  }
}
export default connect(({ capitalDetailsM, loading, globalM }) => ({
  capitalDetailsM,
  loading: loading.effects['capitalDetailsM/getSearch'],
  globalM,
}))(CapitalDetails);
